<template>
  <div class="app-container business-detail details">
    <el-row :gutter="24">
      <el-col :span="5" class="details-left box-card">
        <el-card>
          <div class="details-left-top details-left-box">
            <div class="top">
              <svg-icon
                :icon-class="'svg_xmgl'"
                class="block w-80px h-80px m-auto mb-15px"
              />
              <p style="font-size: 18px; color: #000; font-weight: 600">
                {{ baseInfo.titleName }}
              </p>
            </div>
          </div>
          <div class="details-left-box">
            <div class="cnt">
              <el-row :gutter="24" class="xmzcgk">
                <el-col :span="12">
                  <el-button
                    class="w-100%"
                    plain
                    type="primary"
                    @click="clickFn('followUp')"
                    >写新跟进</el-button
                  >
                </el-col>
                <el-col
                  v-hasPermi="['salesManage:business:transfer']"
                  :span="12"
                >
                  <el-button
                    class="w-100%"
                    plain
                    type="primary"
                    @click="toBusiness"
                    >转移商机</el-button
                  >
                </el-col>
                <el-col :span="12">
                  <el-button
                    class="w-100%"
                    plain
                    type="primary"
                    @click="clickFn('order')"
                    >转为订单</el-button
                  >
                </el-col>

                <el-col :span="12" class="dropdown">
                  <el-dropdown>
                    <el-button class="w-100% px-10" plain type="primary"
                      >添 加</el-button
                    >
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item>产品报价</el-dropdown-item>
                        <el-dropdown-item
                          v-if="baseInfo.contactId != baseInfo.customerId"
                          @click="clickFn('contacts')"
                          >联系人</el-dropdown-item
                        >
                        <el-dropdown-item @click="clickFn('appendix')"
                          >附件</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-col>
                <el-col :span="12" class="dropdown">
                  <el-button
                    class="w-100% px-10"
                    plain
                    type="primary"
                    @click="clickFn('task')"
                    >新建任务</el-button
                  >
                  <!-- <el-dropdown>
                    <el-button class="w-100% px-10" type="primary" plain @click="clickFn('task')">新建任务</el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="clickFn('followTask')"
                          >跟进任务</el-dropdown-item
                        >
                        <el-dropdown-item @click="clickFn('task')"
                          >普通任务</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown> -->
                </el-col>
                <!-- <el-col :span="12">
                  <el-button class="w-100%" type="primary" plain
                    >添加协作</el-button
                  >
                </el-col> -->
              </el-row>
            </div>
          </div>
          <div class="details-left-box">
            <div class="title">商机信息</div>
            <ul class="cnt qzbm">
              <li>
                <el-icon><Notebook /></el-icon>
                <label>客户名称</label>
                <p>{{ baseInfo.customerName }}</p>
              </li>
              <li>
                <el-icon><Notebook /></el-icon>
                <label>联系人</label>
                <p>{{ baseInfo.contactName }}</p>
              </li>
              <li>
                <el-icon><Notebook /></el-icon>
                <label>项目类型</label>
                <p>
                  {{
                    project_type.find(
                      item => item.value == baseInfo.projectType
                    )
                      ? project_type.find(
                          item => item.value == baseInfo.projectType
                        ).label
                      : '--'
                  }}
                </p>
              </li>
              <li>
                <el-icon><Notebook /></el-icon>
                <label>商机阶段</label>
                <p>
                  {{
                    business_stage.find(item => item.value == baseInfo.status)
                      ? business_stage.find(
                          item => item.value == baseInfo.status
                        ).label
                      : '--'
                  }}
                </p>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :span="19" class="box-card">
        <el-card class="details-right" style="min-height: 100%">
          <el-tabs
            v-model="activeTabsName"
            class="details-right-tabs"
            @tab-click="handleClick"
          >
            <el-tab-pane label="审批记录" name="9">
              <ApprovalRecord
                :baseDetail="recordData"
                v-if="activeTabsName == '9'"
              />
            </el-tab-pane>
            <el-tab-pane label="概况信息" name="1">
              <baseInfoForm
                v-if="activeTabsName == '1'"
                :baseInfo="baseInfo"
                :sysInfo="sysInfo"
              />
            </el-tab-pane>
            <el-tab-pane
              v-if="baseInfo.contactId != baseInfo.customerId"
              label="联系人"
              name="2"
            >
              <contactForm
                v-if="activeTabsName == '2'"
                :businessId="businessId"
              />
            </el-tab-pane>
            <el-tab-pane label="跟进记录" name="3">
              <FollowUpForm
                v-if="activeTabsName == '3'"
                :tableParam="followUpParam"
              />
            </el-tab-pane>
            <el-tab-pane label="任务详情" name="4">
              <taskDetailsForm
                v-if="activeTabsName == '4'"
                :taskParam="taskParam"
              ></taskDetailsForm>
            </el-tab-pane>
            <el-tab-pane label="关联订单" name="5">
              <orderFrom
                v-if="activeTabsName == '5'"
                :tableParam="orderInfoFrom"
              />
            </el-tab-pane>
            <el-tab-pane label="关联合同" name="5_1">
              <relatedContracts
                v-if="activeTabsName == '5_1'"
                :tableParam="{
                  businessOpportunityId: baseInfo.id
                }"
              />
            </el-tab-pane>
            <el-tab-pane label="旧ERP历史订单" name="5_2">
              <erpOrder
                v-if="activeTabsName == '5_2'"
                :tableParam="erpInfoFrom"
              />
            </el-tab-pane>
            <el-tab-pane label="产品报价" name="6">
              <productForm
                v-if="activeTabsName == '6'"
                :productInfo="productInfo"
              />
            </el-tab-pane>
            <el-tab-pane label="相关附件" name="7">
              <AppendixForm
                v-if="activeTabsName == '7'"
                :tableParam="followUpParam"
              />
            </el-tab-pane>
            <el-tab-pane label="操作日志" name="8">
              <OperationForm
                v-if="activeTabsName == '8'"
                :tableParam="followUpParam"
              />
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
    <!-- 跟进 -->
    <FollowUp :dialogParam="followUpParam" @close="closeFn"></FollowUp>
    <!-- 添加附件弹窗 -->
    <Appendix :dialogParam="appendixParam" @close="closeFn"></Appendix>
    <!-- 新建任务 -->
    <TaskFrom :dialogParam="taskParam" @closeDialog="closeFn"></TaskFrom>

    <!-- 转移商机弹窗 -->
    <el-dialog
      v-model="transferDialog.open"
      :close-on-click-modal="false"
      :title="transferDialog.title"
      width="40%"
    >
      <el-form
        ref="formRules"
        :model="transferForm"
        :rules="formStopRules"
        label-width="120px"
        status-icon
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="客户名称" prop="customerName">
              <el-input
                v-model="transferForm.customerName"
                disabled
                placeholder="请输入客户名称"
              />
            </el-form-item>
            <el-form-item label="转移给" prop="userName">
              <el-input
                v-model="transferForm.userName"
                placeholder="请选择人员"
                @focus="selectUserFn('userId')"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="transferDialog.open = false">取 消</el-button>
          <el-button type="primary" @click="handleStopSubmit">保存</el-button>
        </span></template
      >
    </el-dialog>
    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
      @ok="selectDialogData"
    />
  </div>
</template>

<script name="businessDetails" setup>
import { reactive, getCurrentInstance, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import baseInfoForm from './modules/basicInfo.vue'
import productForm from './modules/productForm.vue'
import taskDetailsForm from './modules/taskDetails.vue'
import contactForm from '@/views/customerManage/customerModules/customerDetails/modules/CustomerContact.vue'
import ApprovalRecord from '@/views/salesManage/indentManage/salesOrder/modules/approvalRecord'
import FollowUpForm from '@/businessComponents/FollowUpList' //跟进
import orderFrom from '@/businessComponents/DetailsOrderList' //关联订单
import relatedContracts from './modules/relatedContracts.vue'
import erpOrder from './modules/erpOrder.vue'
import AppendixForm from '@/businessComponents/AppendixList' //相关附件
import OperationForm from '@/businessComponents/OperationLog'
import TaskFrom from '@/views/rsgl/taskManage/modules/add.vue'

import {
  getBusinessOpportunityDetail,
  transferOpportunity
} from '@/api/salesManage/businessManage'
import { getOrderList } from '@/api/salesManage/contractManage' //关联订单接口
import { getDept } from '@/api/system/dept'
// import { getTreeNodeByParam, getUniqueUserId } from '@/utils/commo'
import useCommonStore from '@/store/modules/common'
import { parseTime } from '@/utils/ruoyi'
import { addManage } from '@/api/system/notice'

import FollowUp from '@/businessComponents/FollowUp'
import Appendix from '@/businessComponents/Appendix'
import { business_stage, project_type } from '@/hooks/dict/business.js'

const commonStore = useCommonStore()
const userStore = useUserStore()
const { proxy } = getCurrentInstance()
// 通用数据store
const router = useRouter()
const route = useRoute()
let businessId = ref('')
const data = reactive({
  productInfo: [],
  baseInfo: {},
  sysInfo: {},
  taskParam: {}, //普通任务
  followUpParam: {}, //跟进
  orderInfoFrom: {}, //订单
  appendixParam: {}, //附件
  activeTabsName: '1' //分标签name
})
const {
  baseInfo,
  sysInfo,
  activeTabsName,
  taskParam,
  followUpParam,
  orderInfoFrom,
  appendixParam,
  productInfo
} = toRefs(data)

watch(
  [() => route],
  async val => {
    if (route.query && route.query.tabPane) {
      activeTabsName.value = route.query.tabPane
    }
    // init()
  },
  {
    deep: true,
    immediate: true
  }
)
const recordData = ref({}) //审批记录数据
function handleClick(tab) {
  console.log('tab', tab.props.name)
  if (tab.props.name == '1') {
    getBusinessDetails()
  } else if (tab.props.name == '2') {
    businessId.value = baseInfo.value.customerId
  } else if (tab.props.name == '4') {
    // businessId.value = route.query.id
    taskParam.value.businessType = '4' //商机
    taskParam.value.businessId = baseInfo.value.id //列表id
    taskParam.value.businessName = baseInfo.value.titleName //列表标题
  } else if (tab.props.name == '5') {
    orderInfoFrom.value = {
      id: baseInfo.value.customerId,
      name: baseInfo.value.customerName,
      type: 'customer'
    }
  } else if (tab.props.name == '9') {
    console.log(' baseInfo.value==>', baseInfo.value)
    recordData.value = {
      ...baseInfo.value,
      titleName: '商机审批'
    }
  }
}
async function init() {
  await getBusinessDetails()
  /*** 跟进情况 操作日志 附件列表等模块 */
  await setParams()
}
init()
/**旧ERP历史订单 gbq 2024/6/21*/
const erpInfoFrom = ref({}) //erp 历史订单参数
async function getBusinessDetails() {
  const response = await getBusinessOpportunityDetail(route.query.id)
  baseInfo.value = response.data
  //传给旧ERP历史订单的参数
  erpInfoFrom.value = {
    id: response.data.id,
    ctaxcustname: response.data.customerName,
    ctaxcustid: response.data.customerId,
    csccode: response.data.customerTaxcode
  }
  productInfo.value = response.data.productList
  getDept(response.data.deptId).then(res => {
    baseInfo.value.deptName = res.data.deptName
  })
  getDept(response.data.companyId).then(res => {
    baseInfo.value.orgName = res.data.deptName
  })
}

/*** 跟进情况 操作日志 附件列表等模块 */
const setParams = () => {
  followUpParam.value = {
    businessId: baseInfo.value.id, //列表id
    busineName: baseInfo.value.customerName, //客户名称
    tableName: 'ord_business_opportunity'
  }
}

const clickFn = type => {
  console.log('type', type)
  switch (type) {
    case 'contacts':
      // 联系人
      addContacts()
      break
    case 'order':
      // 订单
      let obj = {
        customerId: baseInfo.value.customerId,
        customerName: baseInfo.value.customerName,
        customerType: 'customer'
      }
      router.push({
        path: '/sales/indent/salesOrderForm',
        query: { salesOrderData: JSON.stringify(obj) }
      })

      break
    case 'task':
      // 普通任务
      //   taskParam.value.isVisible = true
      //   taskParam.value.businessType = '4' //商机
      //   taskParam.value.businessId = baseInfo.value.id
      //   taskParam.value.businessName = baseInfo.value.titleName
      //   taskParam.value.remark = baseInfo.value.projectDemand
      let object = {
        businessType: '4',
        businessId: baseInfo.value.id,
        businessName: baseInfo.value.titleName,
        remark: baseInfo.value.projectDemand
      }
      router.push({
        path: '/rsgl/other/addTasking',
        query: { taskParam: JSON.stringify(object) }
      })

      break
    case 'followTask':
      // 更进任务

      break

    case 'followUp':
      // 跟进
      followUpParam.value.isVisible = true
      followUpParam.value.tableName = 'ord_business_opportunity'
      followUpParam.value.businessId = baseInfo.value.id //商机id
      followUpParam.value.customer = baseInfo.value.customerName //客户名称
      followUpParam.value.linkId = baseInfo.value.contactId
        ? baseInfo.value.contactId
        : baseInfo.value.customerId //'联系人id'
      followUpParam.value.linkName = baseInfo.value.contactName //'联系人名称'
      followUpParam.value.status = baseInfo.value.status //商机状态
      break
    case 'appendix':
      // 附件
      appendixParam.value.isVisible = true
      appendixParam.value.tableName = 'ord_business_opportunity'
      appendixParam.value.businessId = baseInfo.value.id

      break
  }
}
// 组件关闭隐藏
const closeFn = row => {
  switch (row) {
    case 'task':
      // 新建任务
      taskParam.value.isVisible = false
      break
    case 'order':
      // 订单

      break
    case 'followUp':
      // 跟进
      followUpParam.value.isVisible = false
      setParams()
      break
    case 'appendix':
      // 附件
      appendixParam.value.isVisible = false
      setParams()
      break
  }
}
function addContacts() {
  router.push({
    path: '/customerManage/contactsModules/contactsAdd',
    query: {
      flag: 'add',
      customerId: baseInfo.value.customerId
    }
  })
}

const dialogParam = ref({})
/**
 * 人员选择
 * @param keyName
 */
function selectUserFn(keyName) {
  switch (keyName) {
    case 'userId':
      dialogParam.value.type = keyName
      dialogParam.value.title = '请选择人员'
      dialogParam.value.isDialog = true
      dialogParam.value.multiple = false
      dialogParam.value.checkStrictly = false
      dialogParam.value.apiParams = {
        disabled: 'true',
        deptId:
          useUserStore().user['orgId'] == '484'
            ? undefined
            : useUserStore().user['orgId']
      }

      dialogParam.value.nodeKey = 'uuid'
      dialogParam.value.defaultCheckedKeys = [transferForm.value[keyName]]
      dialogParam.value.dataType = 'person'
      break
  }
}

// 人员选择确定
const selectDialogData = val => {
  switch (val.type) {
    case 'userId':
      // console.log('val==>', val)
      transferForm.value.userId = val.defaultCheckedKeys[0]
      transferForm.value.userName = val.labelData[0]
      break
  }
}
/* 转移商机开始 */
const transferDialog = ref({
  title: '转移商机',
  open: false
})
const transferForm = ref({
  customerName: [],
  customerId: [],
  userName: '',
  userId: '',
  ids: []
})
const formStopRules = ref({
  userName: [
    {
      required: true,
      message: '请选择人员',
      trigger: ['blur', 'change']
    }
  ]
})

// 清空表单
function resetForm() {
  proxy.resetForm('formRules')
  transferForm.value = {
    customerName: [],
    customerId: [],
    userName: '',
    userId: '',
    ids: []
  }
}
//转移商机
function toBusiness() {
  if (!baseInfo.value) {
    proxy.$modal.msgWarning('请选择要转移的数据')
    return
  }
  resetForm()
  console.log('baseInfo.value', baseInfo.value)
  transferDialog.value.open = true
  transferForm.value.customerName = [baseInfo.value.customerName]
  transferForm.value.ids = [baseInfo.value.id]
}

// 保存转移
function handleStopSubmit() {
  proxy.$refs.formRules.validate((valid, msg) => {
    if (valid) {
      let formData = {
        ids: transferForm.value.ids,
        userId: transferForm.value.userId.replace('U', '')
      }
      transferOpportunity(formData).then(res => {
        proxy.$modal.msgSuccess('转移成功')
        transferDialog.value.open = false

        let mesVoData = {
          businessId: '商机信息_' + new Date().getTime(), //业务ID
          content: '您接收到新的商机信息', //待办内容
          followDate: undefined, //跟进日期
          followType: undefined, //跟进方式
          impSign: '2', //重要程度:0-非常重要，1-重要，2-一般
          receiver: formData.userId, //接收人
          receiverName: undefined, //接收人中文
          reminderMethod: '0', //提醒方式:0-系统站内，1-邮箱，2-短信，允许多个并存，例如:0,1,2
          sendTime: parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'), //发送时间
          sender: useUserStore().user.nickName, //发送人
          serviceType: '16', //业务类型:0-项目，1-订单，2-客户，3-工单，4-任务，5-产品，6-合同，7-公告，8-日程，9-回款, 10-联系人
          title: '您接收到新的商机信息', //待办标题
          type: undefined, //待办类型:0-普通，1-流程
          urgFlag: '2', //紧急程度:0-非常紧急，1-紧急，2-一般
          url: '/sales/businessManage/businessList', //待办链接(多链接用英文逗号隔开)
          urlName: '前往商机' //待办链接名称(多链接名称用英文逗号隔开)
        }
        addManage(mesVoData)
      })
    }
  })
}
/* 转移商机结束 */
</script>

<style lang="scss" scoped>
@import '@/assets/styles/detailsStyle.scss';
.business-detail {
  display: block;
}
.box-card {
  min-height: 85vh;
}
.details {
  padding: 20px;
  background-color: #f4f4f5;
  min-height: calc(100vh - 84px);
  ::v-deep .titleContent .collapse-title {
    font-family: '微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑', sans-serif;
    font-size: 15px;
  }
  ::v-deep .details-left .el-card__body {
    padding: 15px 0px 20px 0px;
  }
  ::v-deep .details-right-tabs .el-tabs__item {
    font-family: '微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑', sans-serif;
    font-weight: 700;
    font-size: 16px;
    padding: 0 30px 0 12px !important;
  }
  ::v-deep .el-checkbox-button__inner {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #e7f3ff !important;
    color: #1890ff;
    border: 1px solid #8bc7ff;
  }
  .dropdown ::v-deep .el-dropdown {
    width: 100%;
  }
  .details-left-top {
    img {
      @include wh(80px, 80px);
      display: block;
      margin: 15px auto;
    }
    .top-img {
      border-radius: 12.5rem;
      background: #ff933c;
      @include wh(80px, 80px);
      margin: 10px auto;
      i {
        background-color: #fff;
        line-height: 80px;
        margin: 18px auto;
      }
    }
  }
  .xmzcgk {
    .el-col {
      margin-bottom: 15px;
      &:last-child {
        margin-bottom: 0px;
      }
    }
  }
}
</style>
